import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:intl/intl.dart';
import '../services/database_service.dart';

class YearlyStatisticsPage extends StatefulWidget {
  final int initialYear;

  const YearlyStatisticsPage({
    super.key,
    required this.initialYear,
  });

  @override
  State<YearlyStatisticsPage> createState() => _YearlyStatisticsPageState();
}

class _YearlyStatisticsPageState extends State<YearlyStatisticsPage> {
  late int _selectedYear;
  late Future<Map<int, MonthlyStats>> _monthlyStatsFuture;
  final _numberFormat = NumberFormat('#,##0.00');

  @override
  void initState() {
    super.initState();
    _selectedYear = widget.initialYear;
    _loadData();
  }

  void _loadData() {
    _monthlyStatsFuture = DatabaseService.instance.getMonthlyStatsByYear(_selectedYear);
  }

  void _changeYear(int delta) {
    setState(() {
      _selectedYear += delta;
      _loadData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.chevron_left),
              onPressed: () => _changeYear(-1),
            ),
            Text('$_selectedYear年'),
            IconButton(
              icon: const Icon(Icons.chevron_right),
              onPressed: DateTime.now().year > _selectedYear
                  ? () => _changeYear(1)
                  : null,
            ),
          ],
        ),
        centerTitle: true,
      ),
      body: FutureBuilder<Map<int, MonthlyStats>>(
        future: _monthlyStatsFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (snapshot.hasError) {
            return Center(child: Text('错误: ${snapshot.error}'));
          }

          final monthlyStats = snapshot.data!;
          final yearlyStats = _calculateYearlyStats(monthlyStats);

          return ListView(
            padding: const EdgeInsets.all(16),
            children: [
              _buildYearlyOverview(yearlyStats),
              const SizedBox(height: 16),
              _buildMonthlyChart(monthlyStats),
              const SizedBox(height: 16),
              _buildMonthlyList(monthlyStats),
            ],
          );
        },
      ),
    );
  }

  Widget _buildYearlyOverview(YearlyStats stats) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildStatItem('年度收入', stats.totalIncome, Colors.green),
                _buildStatItem('年度支出', stats.totalExpense, Colors.red),
              ],
            ),
            const Divider(height: 32),
            _buildStatItem('年度结余', stats.totalBalance, Colors.blue),
          ],
        ),
      ),
    );
  }

  Widget _buildMonthlyChart(Map<int, MonthlyStats> monthlyStats) {
    return AspectRatio(
      aspectRatio: 1.5,
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: BarChart(
            BarChartData(
              alignment: BarChartAlignment.spaceAround,
              maxY: _getMaxAmount(monthlyStats) * 1.2,
              titlesData: FlTitlesData(
                leftTitles: const AxisTitles(
                  sideTitles: SideTitles(showTitles: false),
                ),
                rightTitles: const AxisTitles(
                  sideTitles: SideTitles(showTitles: false),
                ),
                topTitles: const AxisTitles(
                  sideTitles: SideTitles(showTitles: false),
                ),
                bottomTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: (value, meta) {
                      return Text('${value.toInt() + 1}月');
                    },
                  ),
                ),
              ),
              gridData: const FlGridData(show: false),
              borderData: FlBorderData(show: false),
              barGroups: List.generate(12, (index) {
                final stats = monthlyStats[index + 1]!;
                return BarChartGroupData(
                  x: index,
                  barRods: [
                    BarChartRodData(
                      toY: stats.income,
                      color: Colors.green.withOpacity(0.7),
                      width: 8,
                    ),
                    BarChartRodData(
                      toY: stats.expense,
                      color: Colors.red.withOpacity(0.7),
                      width: 8,
                    ),
                  ],
                );
              }),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildMonthlyList(Map<int, MonthlyStats> monthlyStats) {
    return Card(
      child: Column(
        children: [
          ListTile(
            title: const Text('月度明细'),
            subtitle: const Text('绿色：收入 红色：支出 蓝色：结余'),
          ),
          const Divider(height: 1),
          ...List.generate(12, (index) {
            final month = index + 1;
            final stats = monthlyStats[month]!;
            return ListTile(
              title: Text('$month月'),
              subtitle: Row(
                children: [
                  Text(
                    '¥${_numberFormat.format(stats.income)}',
                    style: const TextStyle(color: Colors.green),
                  ),
                  const Text(' / '),
                  Text(
                    '¥${_numberFormat.format(stats.expense)}',
                    style: const TextStyle(color: Colors.red),
                  ),
                ],
              ),
              trailing: Text(
                '¥${_numberFormat.format(stats.balance)}',
                style: TextStyle(
                  color: stats.balance >= 0 ? Colors.blue : Colors.red,
                  fontWeight: FontWeight.bold,
                ),
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, double amount, Color color) {
    return Column(
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          '¥${_numberFormat.format(amount)}',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  double _getMaxAmount(Map<int, MonthlyStats> monthlyStats) {
    double maxAmount = 0;
    for (final stats in monthlyStats.values) {
      maxAmount = [maxAmount, stats.income, stats.expense]
          .reduce((curr, next) => curr > next ? curr : next);
    }
    return maxAmount;
  }

  YearlyStats _calculateYearlyStats(Map<int, MonthlyStats> monthlyStats) {
    var totalIncome = 0.0;
    var totalExpense = 0.0;

    for (final stats in monthlyStats.values) {
      totalIncome += stats.income;
      totalExpense += stats.expense;
    }

    return YearlyStats(
      totalIncome: totalIncome,
      totalExpense: totalExpense,
      totalBalance: totalIncome - totalExpense,
    );
  }
}

class YearlyStats {
  final double totalIncome;
  final double totalExpense;
  final double totalBalance;

  YearlyStats({
    required this.totalIncome,
    required this.totalExpense,
    required this.totalBalance,
  });
} 